import re
import time
import pymongo
import common.gyblog as log
import manage_db.query_db as dm
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service as ChromeService

LOG = log.get_logger()
SERVICE = ChromeService(executable_path="../common/chromedriver.exe")

# 查询条件，空表示全查询
SERIES = '10musume'
YEAR = '2021'

'''
抓取tor优先级：
[ThZu.Cc] > [Thz.la]
1080p > 720p
'''


def download_javbook(find_ans):
    # 连接数据库
    db_client = pymongo.MongoClient(dm.CONNECTION_STR)
    db_database = db_client[dm.DATA_BASE]
    db_col = db_database[dm.DB_COL]

    for f_count, f in enumerate(find_ans):
        url = f['detail_url']
        try:
            # 创建 WebDriver 对象
            driver = webdriver.Chrome(service=SERVICE)
            driver.get(url)
            elements = driver.find_elements(By.XPATH, '/html/body/div[7]/div[position()]/span/a')
            # 遍历元素并获取 href 属性
            tor_ans = []
            for element in elements:
                name = element.text
                ratio = element.text.split('-')[-1]
                if '[ThZu.Cc]' in name and ratio != '720p':
                    tor = element.get_attribute('href')
                    tor_ans.append([name, tor])
            for element in elements:
                name = element.text
                ratio = element.text.split('-')[-1]
                if '[psk.la]' in name and ratio == 'FHD':
                    tor = element.get_attribute('href')
                    tor_ans.append([name, tor])
            for element in elements:
                name = element.text
                if '[JAV] [Uncensored]' in name and '[1080p]' in name:
                    tor = element.get_attribute('href')
                    tor_ans.append([name, tor])
            for element in elements:
                name = element.text
                if '会飞的象' in name:
                    tor = element.get_attribute('href')
                    tor_ans.append([name, tor])
            for element in elements:
                name = element.text
                ratio = element.text.split('-')[-1]
                if ratio == '1080p':
                    tor = element.get_attribute('href')
                    tor_ans.append([name, tor])
            for element in elements:
                name = element.text
                if 'xyz@' in name or 'xyz' in name:
                    tor = element.get_attribute('href')
                    tor_ans.append([name, tor])
            if len(tor_ans) == 0:
                print('{}：没有找到tor,进度{}/{}'.format(url, str(f_count + 1), len(find_ans)))
                LOG.info('{}：没有找到tor'.format(url))
            else:
                query = {'detail_url': url}
                new_values = {"$set": {"tor": tor_ans[0][1], "tor_name": tor_ans[0][0]}}
                db_col.update_one(query, new_values)
                print('已插入:{},{},{},进度{}/{}'.format(tor_ans[0][1], tor_ans[0][0], url, str(f_count + 1),
                                                         len(find_ans)))
                LOG.info('已插入:{},{},{},进度{}/{}'.format(tor_ans[0][1], tor_ans[0][0], url, str(f_count + 1),
                                                            len(find_ans)))
            driver.close()
            time.sleep(1)
        except Exception as e:
            print('{} error:'.format(url), repr(e))
    db_client.close()


def download_javbook_all(find_ans):
    # 连接数据库
    db_client = pymongo.MongoClient(dm.CONNECTION_STR)
    db_database = db_client[dm.DATA_BASE]
    db_col = db_database[dm.DB_COL]

    for f_count, f in enumerate(find_ans):
        url = f['detail_url']
        try:
            # 创建 WebDriver 对象
            driver = webdriver.Chrome(service=SERVICE)
            driver.get(url)
            elements = driver.find_elements(By.XPATH, '/html/body/div[7]/div[position()]/span/a')
            # 遍历元素并获取 href 属性
            tor_ans = []
            for element in elements:
                name = element.text
                ratio = element.text.split('-')[-1]
                if ratio == '-FHD':
                    tor = element.get_attribute('href')
                    tor_ans.append([name, tor])
            for element in elements:
                name = element.text
                tor = element.get_attribute('href')
                tor_ans.append([name, tor])
            if len(tor_ans) == 0:
                print('{}：没有找到tor,进度{}/{}'.format(url, str(f_count + 1), len(find_ans)))
                LOG.info('{}：没有找到tor'.format(url))
            else:
                query = {'detail_url': url}
                new_values = {"$set": {"tor": tor_ans[0][1], "tor_name": tor_ans[0][0]}}
                db_col.update_one(query, new_values)
                print('已插入:{},{},{},进度{}/{}'.format(tor_ans[0][1], tor_ans[0][0], url, str(f_count + 1),
                                                         len(find_ans)))
                LOG.info('已插入:{},{},{},进度{}/{}'.format(tor_ans[0][1], tor_ans[0][0], url, str(f_count + 1),
                                                            len(find_ans)))
            driver.close()
            time.sleep(1)
        except Exception as e:
            print('{} error:'.format(url), repr(e))
    db_client.close()


def download_sukebei(find_ans, keyword, trust):
    # 连接数据库
    db_client = pymongo.MongoClient(dm.CONNECTION_STR)
    db_database = db_client[dm.DATA_BASE]
    db_col = db_database[dm.DB_COL]

    for f_count, f in enumerate(find_ans):
        if trust == 'Y':
            url = 'https://sukebei.nyaa.si/?f=2&c=0_0&q={}-{}'.format(f['num'], keyword)
        else:
            url = 'https://sukebei.nyaa.si/?f=0&c=0_0&q={}-{}'.format(f['num'], keyword)
        detail_url = f['detail_url']
        try:
            # 创建 WebDriver 对象
            driver = webdriver.Chrome(service=SERVICE)
            driver.get(url)
            # 使用 XPath 定位元素
            elements = driver.page_source
            tors = re.findall("magnet:\?xt=urn:.*?&amp", elements)

            if len(tors) == 0:
                print('{}：没有找到tor,进度{}/{}'.format(url, str(f_count + 1), len(find_ans)))
                LOG.info('{}：没有找到tor'.format(url))
            else:
                query = {'detail_url': detail_url}
                new_values = {"$set": {"tor": tors[0], "tor_name": 'subebei'}}
                db_col.update_one(query, new_values)
                print('查询：{}，查询到{}个'.format(url, len(tors)))
                LOG.info('查询：{}，查询到{}个'.format(url, len(tors)))
                print('已插入:{},{},进度{}/{}'.format(tors[0], detail_url, str(f_count + 1), len(find_ans)))
                LOG.info('已插入:{},{},进度{}/{}'.format(tors[0], detail_url, str(f_count + 1), len(find_ans)))
            driver.close()
            time.sleep(1)
        except Exception as e:
            print('{} error:'.format(url), repr(e))


def download_sukebei_fc2(not_exist):
    # 连接数据库
    db_client = pymongo.MongoClient(dm.CONNECTION_STR)
    db_database = db_client[dm.DATA_BASE]
    db_col = db_database['fc2_manage_record']

    tor_ans = []
    for f_count, f in enumerate(not_exist):
        num = str(f).replace('FC2-', '')
        url = 'https://sukebei.nyaa.si/?f=2&c=0_0&q={}'.format(num)

        try:
            # 创建 WebDriver 对象
            driver = webdriver.Chrome(service=SERVICE)
            driver.get(url)
            # 使用 XPath 定位元素
            elements = driver.page_source
            tors = re.findall("magnet:\?xt=urn:.*?&amp", elements)

            if len(tors) == 0:
                print('{}：没有找到tor,进度{}/{}'.format(url, str(f_count + 1), len(not_exist)))
            else:
                print('{}：{}:查询到{}个,进度{}/{}'.format(f, url, len(tors), str(f_count + 1), len(not_exist)))
                for tor in tors:
                    print(tor)
                tor_ans.append(tors[-1])

                # 记录到数据库
                my_dict = {'num': f, 'tor': tors[-1]}
                db_col.insert_one(my_dict)

            driver.close()
            time.sleep(1)
        except Exception as e:
            print('{} error:'.format(url), repr(e))
    db_client.close()
    return tor_ans

def download_sukebei_by_keyword(keyword):
    for i in range(15):
        url = 'https://sukebei.nyaa.si/?f=2&c=0_0&q={}&p={}'.format(keyword,str(i))
        # 创建 WebDriver 对象
        driver = webdriver.Chrome(service=SERVICE)
        driver.get(url)
        # 使用 XPath 定位元素
        elements = driver.page_source
        tors = re.findall("magnet:\?xt=urn:.*?&amp", elements)

        if len(tors) == 0:
            print('{}：没有找到tor'.format(url))
        else:
            print('{}：查询到{}个'.format(url, len(tors)))
            for tor in tors:
                print(tor)

